<template>
  <div class="website-table">
    <div style="margin-bottom: 16px; display: flex; justify-content: space-between">
      <el-button 
        type="primary" 
        :icon="Plus"
        @click="handleAddWebsite"
      >
        添加网站
      </el-button>
      
      <el-popconfirm
        title="确定要删除所有网站吗？此操作不可恢复。"
        @confirm="handleDeleteAll"
        confirm-button-text="删除"
        cancel-button-text="取消"
      >
        <template #reference>
          <el-button type="danger">删除所有网站</el-button>
        </template>
      </el-popconfirm>
    </div>
    
    <el-table 
      :data="websites"
      :loading="isLoading"
      row-key="_id"
      :row-class-name="getRowClassName"
      @row-click="handleRowClick"
      style="width: 100%"
    >
      <el-table-column label="序号" width="60" type="index" :index="1" />
      <el-table-column prop="name" label="网站名称" min-width="120">
        <template #default="{ row }">
          <span 
            :style="{ 
              fontWeight: row._id === currentWebsiteId ? 'bold' : 'normal',
              color: row._id === currentWebsiteId ? 'var(--el-color-primary)' : 'inherit'
            }"
          >
            {{ row.name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="domain" label="域名" />
      <el-table-column prop="description" label="描述" show-overflow-tooltip />
      <el-table-column prop="trackingId" label="跟踪ID" width="280" />
      <el-table-column prop="isActive" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.isActive ? 'success' : 'danger'">
            {{ row.isActive ? '活跃' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="{ row }">
          {{ new Date(row.createdAt).toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
          <el-space>
            <el-button 
              :type="row._id === currentWebsiteId ? 'default' : 'primary'"
              size="small" 
              @click.stop="handleViewStats(row)"
            >
              {{ row._id === currentWebsiteId ? '当前' : '统计' }}
            </el-button>
            <el-dropdown @command="(cmd) => handleCommand(cmd, row)">
              <el-button size="small" :icon="MoreFilled" @click.stop />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="edit" :icon="Edit">编辑</el-dropdown-item>
                  <el-dropdown-item command="stats" :icon="DataAnalysis">查看统计</el-dropdown-item>
                  <el-dropdown-item command="embed" :icon="DocumentCopy">获取嵌入代码</el-dropdown-item>
                  <el-dropdown-item command="delete" :icon="Delete" divided>删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-space>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑网站模态框 -->
    <el-dialog
      v-model="editModalVisible"
      title="编辑网站"
      :close-on-click-modal="false"
      width="600px"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-form-item label="网站名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入网站名称" />
        </el-form-item>
        <el-form-item label="域名" prop="domain">
          <el-input v-model="editForm.domain" placeholder="例如: example.com" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入网站描述（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCancelEdit">取消</el-button>
        <el-button type="primary" @click="handleSubmitEdit" :loading="isLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, MoreFilled, Edit, DataAnalysis, DocumentCopy, Delete } from '@element-plus/icons-vue'

interface Website {
  _id: string | number
  id?: string | number
  name: string
  domain: string
  description?: string
  trackingId?: string
  isActive?: boolean
  createdAt?: string
}

const props = defineProps<{
  websites: Website[]
  isLoading?: boolean
  currentWebsiteId?: string | number | null
}>()

const emit = defineEmits<{
  addWebsite: []
  viewStats: [website: Website]
  viewLogs: [website: Website]
  getEmbedCode: [website: Website]
  updateWebsite: [id: string | number, values: any]
  deleteWebsite: [id: string | number]
  deleteAllWebsites: []
}>()

const editModalVisible = ref(false)
const editingWebsite = ref<Website | null>(null)
const editFormRef = ref()
const editForm = ref({
  name: '',
  domain: '',
  description: ''
})

const editRules = {
  name: [{ required: true, message: '请输入网站名称', trigger: 'blur' }],
  domain: [{ required: true, message: '请输入域名', trigger: 'blur' }]
}

const getRowClassName = ({ row }: { row: Website }) => {
  return row._id === props.currentWebsiteId ? 'selected-row' : ''
}

const handleAddWebsite = () => {
  emit('addWebsite')
}

const handleDeleteAll = () => {
  emit('deleteAllWebsites')
}

const handleViewStats = (website: Website) => {
  emit('viewStats', website)
}

const handleRowClick = (row: Website) => {
  if (row._id !== props.currentWebsiteId) {
    emit('viewStats', row)
  }
}

const handleEditClick = (row: Website) => {
  editingWebsite.value = row
  editForm.value = {
    name: row.name,
    domain: row.domain,
    description: row.description || ''
  }
  editModalVisible.value = true
}

const handleDeleteClick = (row: Website) => {
  ElMessageBox.confirm(
    `确定要删除网站 "${row.name}" 吗？此操作不可恢复。`,
    '确认删除',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    emit('deleteWebsite', row._id)
  }).catch(() => {})
}

const handleCommand = (cmd: string, row: Website) => {
  const actions = {
    edit: () => handleEditClick(row),
    stats: () => emit('viewStats', row),
    embed: () => emit('getEmbedCode', row),
    delete: () => handleDeleteClick(row)
  }
  actions[cmd as keyof typeof actions]?.()
}


const handleSubmitEdit = async () => {
  if (!editFormRef.value || !editingWebsite.value) return
  
  const isValid = await editFormRef.value.validate().catch(() => false)
  if (isValid) {
    emit('updateWebsite', editingWebsite.value._id, editForm.value)
    editModalVisible.value = false
    editingWebsite.value = null
  }
}

const handleCancelEdit = () => {
  editModalVisible.value = false
  editingWebsite.value = null
  editFormRef.value?.resetFields()
}

</script>

<style scoped lang="scss">
.website-table {
  margin-bottom: 24px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

:deep(.el-table__header-wrapper .el-table__header th) {
  background-color: var(--table-header-bg, #fafafa);
  font-weight: 600;
}

:deep(.selected-row) {
  background-color: rgba(64, 158, 255, 0.1);
  
  &:hover {
    background-color: rgba(64, 158, 255, 0.2) !important;
  }
}

:deep(.el-table__row) {
  cursor: pointer;
  
  &:hover {
    background-color: rgba(64, 158, 255, 0.05) !important;
  }
}
</style>

